﻿#include "headspacingsheetdialog.h"
#include "ui_headspacingsheetdialog.h"

#define ROW_NUM          10    //按钮行数
#define COLUMN_NUM    5    //按钮列数

HeadSpacingSheetDialog::HeadSpacingSheetDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::HeadSpacingSheetDialog)
{
    ui->setupUi(this);
    setWindowFlags (Qt::Window | Qt::FramelessWindowHint);
    setWindowModality(Qt::ApplicationModal);

    initWidget();
    initControl();

    memset(&m_data, 0, sizeof(DsrHeadEx62));
    m_dataNums = 0;
    refreshPageUi();
}

HeadSpacingSheetDialog::~HeadSpacingSheetDialog()
{
    delete ui;
}


void HeadSpacingSheetDialog::refreshPageUi()
{
    //清空全部按钮数据
    foreach (QPushButton* button, m_sheetBtnList) {
        button->setText("");
        button->setEnabled(false);
        button->setVisible(false);
    }

    //计算页码范围
    m_pageNums = m_dataNums / ROW_NUM;//向上取整 总页数
    m_pageNums = (m_dataNums % ROW_NUM == 0) ? m_pageNums : m_pageNums + 1;

    if (m_curPages > m_pageNums)// 当前页
    {
        m_curPages = m_pageNums;
    }
    if (m_curPages < 1)
    {
        m_curPages = 1;
    }

    //刷新列值
    for(int i = 0; i < ROW_NUM; i++)
    {
        int rowNum = i + 1 + (m_curPages -1) * ROW_NUM;
        //如果超过最大值则不显示
        if(rowNum > m_dataNums){
            m_sheetVLabelList[i]->setVisible(false);
        }
        else{
            m_sheetVLabelList[i]->setText(QString("%1").arg(rowNum));
            m_sheetVLabelList[i]->setFont(fontSize_M());
            m_sheetVLabelList[i]->setVisible(true);
            m_sheetVLabelList[i]->setStyleSheet(titleTextColour());
            m_sheetVLabelList[i]->setAlignment(Qt::AlignRight);
            m_sheetVLabelList[i]->setAlignment(Qt::AlignCenter);
        }
    }

    //显示已存在的数据
    for(int i = 0; i < ROW_NUM; i++){
        int labelIdx = (m_curPages - 1) * ROW_NUM + i;
        if(labelIdx > m_dataNums - 1)
        {
            //超过机头间距总段数
            break;
        }
        else
        {
            m_sheetBtnList[i * COLUMN_NUM + 0 ]->setText(charToQString(m_data.headEnableSpacing[labelIdx].iswork));
            m_sheetBtnList[i * COLUMN_NUM + 1 ]->setText(intDiv10(m_data.headEnableSpacing[labelIdx].distance1_2));
            m_sheetBtnList[i * COLUMN_NUM + 2 ]->setText(intDiv10(m_data.headEnableSpacing[labelIdx].distance1_3));
            m_sheetBtnList[i * COLUMN_NUM + 3 ]->setText(intDiv10(m_data.headEnableSpacing[labelIdx].distance1_4));
            m_sheetBtnList[i * COLUMN_NUM + 4 ]->setText(intDiv10(m_data.headEnableSpacing[labelIdx].distance1_5));

            m_sheetBtnList[i * COLUMN_NUM + 0 ]->setEnabled(true);
            m_sheetBtnList[i * COLUMN_NUM + 1 ]->setEnabled(true);
            m_sheetBtnList[i * COLUMN_NUM + 2 ]->setEnabled(true);
            m_sheetBtnList[i * COLUMN_NUM + 3 ]->setEnabled(true);
            m_sheetBtnList[i * COLUMN_NUM + 4 ]->setEnabled(true);

            m_sheetBtnList[i * COLUMN_NUM + 0 ]->setVisible(true);
            m_sheetBtnList[i * COLUMN_NUM + 1 ]->setVisible(true);
            m_sheetBtnList[i * COLUMN_NUM + 2 ]->setVisible(true);
            m_sheetBtnList[i * COLUMN_NUM + 3 ]->setVisible(true);
            m_sheetBtnList[i * COLUMN_NUM + 4 ]->setVisible(true);
        }
    }

    // 页信息
    QString str = tr("pageNum: ") + QString("%1/%2").arg(m_curPages).arg(m_pageNums);//页数:
    ui->labelPageNum->setText(str);
}

void HeadSpacingSheetDialog::setTypeLogo(QString tStyle)
{
    ui->buttonTypeLogo->setUnPreBtnLogo(tStyle);
}

void HeadSpacingSheetDialog::setMainTitle(QString str)
{
    ui->labelMainTitle->setText(str);
}

void HeadSpacingSheetDialog::setSubTitle(QString str)
{
    ui->labelSubTitle->setText(str);
}

void HeadSpacingSheetDialog::on_buttonPgUp_clicked()
{
    m_curPages--;
    refreshPageUi();
}

void HeadSpacingSheetDialog::slotSheetBtnClicked()
{
    MyButton *button = (MyButton*) this->sender() ;
    int index = m_sheetBtnList.indexOf(button);
    int rowIndex = index / COLUMN_NUM;
    int column = index % COLUMN_NUM;

//    qDebug()<< QString("点击了第%1个按钮").arg(index);
//    qDebug()<< rowIndex ; //行
//    qDebug()<< column;  //列

    int listIndex = rowIndex + (m_curPages - 1) * ROW_NUM;
    qDebug()<< "listIndex:" << listIndex;

    if(column == 0) //机头开关设置 按bit位
    {
        //获取bit位的数据，存入内存
        McHeadDialog mcHeadDialog(this);
        mcHeadDialog.setChar(m_data.headEnableSpacing[listIndex].iswork);
        int result = mcHeadDialog.exec();
        if(result == 1)
        {
            unsigned char headIsWork = mcHeadDialog.getChar();
            m_data.headEnableSpacing[listIndex].iswork = headIsWork; //修改内存的值
            button->setText(charToQString(headIsWork));
        }
    }
    else
    {
        //机头间距参数设置
        NumerInputDialog ndlg(this);
        ndlg.setTitleStr("Step distance");//跨步距离
        ndlg.setUnitStr("0.1mm");
        ndlg.setValueAndRange((int)button->text().toDouble()*10, 0, 50000, 1); // 界面中的数*10 为内存中的实际值
        int rslt = ndlg.exec();

        if(rslt == 1){
            s32 val = ndlg.getValue();     // 0.1mm  界面输入500.1 此时的数是5001，但是界面上还是需要显示500.1
            //修改界面的值
            button->setText(intDiv10(val));

            //修改内存的值
            HeadTable *item = &m_data.headEnableSpacing[listIndex];
            switch (column)
            {
            case 1:
                item->distance1_2 = val;
                break;
            case 2:
                item->distance1_3 = val;
                break;
            case 3:
                item->distance1_4 = val;
                break;
            case 4:
                item->distance1_5 = val;
                break;
            case 5:
                item->distance1_6 = val;
                break;
            case 6:
                item->distance1_7 = val;
                break;
            case 7:
                item->distance1_8 = val;
                break;

            default:
                break;
            }
        }

    }

}

void HeadSpacingSheetDialog::setHeadData(DsrHeadEx62 data)
{
    m_data = data;
    m_curPages = 1;
    refreshPageUi();
}

DsrHeadEx62 HeadSpacingSheetDialog::getHeadData()
{
    return m_data;
}

void HeadSpacingSheetDialog::initDsrFileInfo(QString fileName)
{
    QFileInfo fileInfo(fileName);
    QString  suffer = fileInfo.suffix().toUpper();
    if(suffer != "DSR"){
        return ;
    }
    //根据文件名加载
    m_fileName = fileName;
    DataFileDsr dsr;
    dsr.initFile(m_fileName);
    dsr.convertDataToEmbAbs();
    m_data = dsr.get62ExHead();
    m_dataNums = dsr.getStepNums();
    refreshPageUi();
}

void HeadSpacingSheetDialog::setStepNums(int dataNums)
{
    m_dataNums = dataNums;
    refreshPageUi();
}

QString HeadSpacingSheetDialog::detectUsb()
{
    QString usbPath = "";

#ifdef Q_OS_LINUX
    QDir dir(LINUXUSBPATH);
    if(!dir.exists())
    {
        usbPath = "";
    }
    else
    {
        usbPath = LINUXUSBPATH;
    }
#endif

#ifdef Q_OS_WIN
    QFileInfoList list =  QDir::drives();

    for(int i = 0; i<list.count(); i++)
    {
        UINT ret = GetDriveType((WCHAR *) list.at(i).filePath().utf16());
        if(ret == DRIVE_REMOVABLE)
        {
            usbPath = list.at(i).filePath();
            break;
        }
    }
#endif
    return usbPath;
}

void HeadSpacingSheetDialog::initWidget()
{
    m_sheetBtnList.clear();
    m_sheetHLabelList.clear();
    m_sheetVLabelList.clear();
    m_itemXList.clear();
    m_itemYList.clear();

    m_btnPerPage = COLUMN_NUM * ROW_NUM;
    m_curPages = 0;
    m_pageNums = 1;

    for(int i = 0; i < ROW_NUM; i++)
    {
        for(int j = 0; j < COLUMN_NUM; j++)
        {
            MyButton *buttonSheet = new MyButton(ui->frameSheet);
            m_sheetBtnList.append(buttonSheet);
            connect(buttonSheet,
                    SIGNAL(clicked()),
                    this,
                    SLOT(slotSheetBtnClicked())
                    );
        }
    }

    for(int i = 0; i < COLUMN_NUM; i++)
    {
        QLabel *labelH = new QLabel(this);
        labelH->setAlignment(Qt::AlignCenter); //设置居中
        m_sheetHLabelList.append(labelH);
    }

    for(int i = 0; i < ROW_NUM; i++)
    {
        QLabel *labelV = new QLabel(this);
        m_sheetVLabelList.append(labelV);
    }
}

void HeadSpacingSheetDialog::initControl()
{
    //根据不同分辨率设置控件的位置和尺寸
    initResolution();
    initControlStyle();//初始化窗体控件样式
}

//初始化窗体控件为任意分辨率
void HeadSpacingSheetDialog::initResolution()
{
    double factoryX = getFactoryX();
    double factoryY = getFactoryY();

    this->resize(GLB_SCR_WIGHT*factoryX,GLB_SCR_HEIGHT*factoryY);
    this->move((GLB_SCR_WIGHT*factoryX-this->width())/2+g_mainWidgetPos.x(),(GLB_SCR_HEIGHT*factoryY-this->height())/2+g_mainWidgetPos.y());
    ui->buttonTypeLogo->setGeometry(GLB_EDGE_WIGHT*factoryX,GLB_EDGE_HEIGHT*factoryY,GLB_LICON_SIZE*factoryX,GLB_LICON_SIZE*factoryY);
    ui->labelMainTitle->setGeometry((GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT)*factoryX,GLB_EDGE_HEIGHT*factoryY,
                                    (GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT*2))*factoryX,GLB_TEXT_L_HEIGHT*factoryY);
    ui->labelSubTitle->setGeometry((GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT+GLB_TAB_WIGHT)*factoryX,(GLB_EDGE_HEIGHT+GLB_LICON_SIZE-GLB_TEXT_HEIGHT)*factoryY,
                                   (GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT+GLB_TAB_WIGHT*2))*factoryX,GLB_TEXT_HEIGHT*factoryY);

    ui->frameBack->setGeometry(0*factoryX,0*factoryY,GLB_SCR_WIGHT*factoryX,GLB_SCR_HEIGHT*factoryY);
    ui->labelPageNum->setGeometry(GLB_EDGE_WIGHT*factoryX,(GLB_SCR_HEIGHT-GLB_TEXT_HEIGHT-GLB_EDGE_WIGHT)*factoryY,(GLB_SCR_WIGHT-GLB_EDGE_WIGHT*2)*factoryX,GLB_TEXT_HEIGHT*factoryY);

    ui->framePageBtn->setGeometry(0*factoryX,(GLB_SCR_HEIGHT-GLB_LBUT_HEIGHT-GLB_EDGE_WIGHT)*factoryY,GLB_SCR_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonPgUp->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*3+GLB_LBUT_WIGHT*4))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonPgDn->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*2+GLB_LBUT_WIGHT*3))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonOk->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*1+GLB_LBUT_WIGHT*2))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonCancel->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*0+GLB_LBUT_WIGHT*1))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);

    ui->frameSheet->setGeometry(10 *factoryX,120*factoryY,1000*factoryX,420*factoryY);

    ui->buttonParaImport->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_MICON_SIZE))*factoryX,(GLB_EDGE_HEIGHT+GLB_LICON_SIZE-GLB_MICON_SIZE)*factoryY,GLB_MICON_SIZE*factoryX,GLB_MICON_SIZE*factoryY);
    ui->buttonParaExport->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*1+GLB_MICON_SIZE*2))*factoryX,(GLB_EDGE_HEIGHT+GLB_LICON_SIZE-GLB_MICON_SIZE)*factoryY,GLB_MICON_SIZE*factoryX,GLB_MICON_SIZE*factoryY);

    //label样式
    ui->labelMainTitle->setFont(fontSize_L());
    ui->labelMainTitle->setStyleSheet(titleTextColour());
    ui->labelSubTitle->setFont(fontSize_M());
    ui->labelSubTitle->setStyleSheet(noteTextColour());
    ui->labelPageNum->setFont(fontSize_M());
    ui->labelPageNum->setStyleSheet(titleTextColour());

    for(int i = 0; i < ROW_NUM; i++)
    {
        for(int j = 0; j < COLUMN_NUM; j++)
        {
            m_sheetBtnList[i*COLUMN_NUM+j]->setGeometry((100+j*160)*factoryX , (30+i*38) *factoryY, 150*factoryX, 32*factoryY);
        }
    }

    for(int i = 0; i < COLUMN_NUM; i++)
    {
        m_sheetHLabelList[i]->setGeometry((180 + i*156) *factoryX, 94*factoryY, 70*factoryX, 40*factoryY);
    }

    for(int i = 0; i < ROW_NUM; i++)
    {
        m_sheetVLabelList[i]->setGeometry(30*factoryX, (149+i*38)*factoryY, 72*factoryX, 32*factoryY);
    }
}


void HeadSpacingSheetDialog::initControlStyle()
{
    SetStyle setControlStyle;
    setControlStyle.setUiName(this->objectName());

    ui->labelPageNum->setText(tr("PageNum: 0/0"));//页数: 0/0
    ui->frameBack->setStyleSheet(transparentStyle());
    QString str = setControlStyle.getStyleSheet(this->objectName());
    ui->frameBack->setStyleSheet(str);
    //四个按钮样式表一样
    ui->buttonPgUp->setStyleSheet(confirmIconStyle());
    ui->buttonPgUp->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonPgUp->objectName()),12);

    ui->buttonPgDn->setStyleSheet(confirmIconStyle());
    ui->buttonPgDn->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonPgDn->objectName()),12);

    ui->buttonOk->setStyleSheet(confirmIconStyle());
    ui->buttonOk->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonOk->objectName()),12);

    ui->buttonCancel->setStyleSheet(confirmIconStyle());
    ui->buttonCancel->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonCancel->objectName()),12);

    ui->buttonParaExport->setStyleSheet(backIconStyle());;
    ui->buttonParaExport->setTopImage(setControlStyle.getTopStyleSheet(ui->buttonParaExport->objectName()));

    ui->buttonParaImport->setStyleSheet(backIconStyle());;
    ui->buttonParaImport->setTopImage(setControlStyle.getTopStyleSheet(ui->buttonParaImport->objectName()));


    for(int i = 0; i < COLUMN_NUM; i++)
    {
        if(i == 0){
             m_sheetHLabelList[i]->setText(QString("1"));
        }
        else
        {
            m_sheetHLabelList[i]->setText(QString("1-%1").arg(i+1));
        }
        m_sheetHLabelList[i]->setFont(fontSize_M());
        m_sheetHLabelList[i]->setStyleSheet(titleTextColour());
        m_sheetHLabelList[i]->setAlignment(Qt::AlignCenter);
        m_sheetHLabelList[i]->setAlignment(Qt::AlignBottom);
    }

    for(int i = 0; i < ROW_NUM; i++)
    {
        m_sheetVLabelList[i]->setText(QString("%1").arg(i+1));
        m_sheetVLabelList[i]->setFont(fontSize_M());
        m_sheetVLabelList[i]->setStyleSheet(titleTextColour());
        m_sheetVLabelList[i]->setAlignment(Qt::AlignRight);
        m_sheetVLabelList[i]->setAlignment(Qt::AlignCenter);
    }

    ui->frameSheet->setStyleSheet(transparentStyle());
    for(int i = 0; i < ROW_NUM; i++)
    {
        for(int j = 0; j < COLUMN_NUM; j++)
        {
            m_sheetBtnList[i*COLUMN_NUM+j]->setStyleSheet(headButtonStyle());
            m_sheetBtnList[i*COLUMN_NUM+j]->setFont(fontSize_M());
        }
    }
}

void HeadSpacingSheetDialog::on_buttonPgDn_clicked()
{
    m_curPages++;
    refreshPageUi();
}

void HeadSpacingSheetDialog::on_buttonOk_clicked()
{
    //数据保存到源文件
    QFile file(m_fileName);
    if(file.open(QIODevice::ReadWrite))
    {
        QByteArray fileData(sizeof(DsrHeadEx62), 0);
        memcpy(fileData.data(), (char*)(&m_data), sizeof(DsrHeadEx62));
        file.seek(sizeof(DsrHead));
        qDebug()<<"HeadSpacingSheetDialog::on_buttonOk_clicked: file.pos:"<<file.pos();
        file.write(fileData);
        file.close();
    }
    else
    {
        qDebug()<<"打开文件错误";
    }
    done(1);
}

void HeadSpacingSheetDialog::on_buttonCancel_clicked()
{
    done(0);
}

void HeadSpacingSheetDialog::on_buttonParaExport_clicked()
{
    //导出参数到u盘
    QString usbPath = detectUsb();
    if(usbPath.size() <=0)
    {
        PromptDialog dialog;
        dialog.initDialog(PromptDialog::BTN_OK);
        dialog.setTitleStr(tr("Prompt"));//提示
        dialog.setContentStr(tr("USB flash drive is not detected!"));//未检测到优盘！
        dialog.exec();
        return ;
    }

    QString hsFileName = QString("%1.hs").arg(QFileInfo(m_fileName).baseName());
    QString pathName = usbPath + hsFileName;
    QFile file(pathName);
    if(file.open(QIODevice::WriteOnly)){
        QDataStream outstream(&file);
        outstream.writeRawData((const char *)&m_data, sizeof(DsrHeadEx62));
        file.close();
        PromptDialog dialog;
        dialog.initDialog(PromptDialog::BTN_OK);
        dialog.setTitleStr(tr("Prompt"));//提示
        dialog.setContentStr(tr("Export successful"));//导出成功！
        dialog.exec();
    }else{
        qDebug()<<"文件打开失败";
    }

}

void HeadSpacingSheetDialog::on_buttonParaImport_clicked()
{
    //从usb导入并刷新ui

    QString usbPath = detectUsb();
    if(usbPath.size() <=0)
    {
        PromptDialog dialog1;
        dialog1.initDialog(PromptDialog::BTN_OK);
        dialog1.setTitleStr(tr("Prompt"));
        dialog1.setContentStr(tr("USB flash drive is not detected!"));//未检测到优盘！
        dialog1.exec();
        return ;
    }

//    FileSelectDialog dialog(m_fileName.left(m_fileName.lastIndexOf("/") + 1), this); //用于无u盘测试
    FileSelectDialog dialog(usbPath, this);

    int result = dialog.exec();
    if(result != 1)
        return;

    QString hsFileStr = dialog.getFileName();
    QString hsFileName = usbPath +hsFileStr;
    //读取文件信息
    QFile hsFile(hsFileName);
    if(hsFile.open(QIODevice::ReadOnly))
    {
        QByteArray array = hsFile.readAll(); //读取文件
        if(array.size() != sizeof(DsrHeadEx62))
            qDebug()<<"hs文件大小错误";

        //保存到文件
        QFile dsrFile(m_fileName);
        if(dsrFile.open(QIODevice::ReadWrite))
        {
            dsrFile.seek(sizeof(DsrHead));
            qDebug()<<dsrFile.pos();
            dsrFile.write(array);
            dsrFile.close();
        }else
        {
            hsFile.close();
            return;
        }

        //保存到界面
        memcpy((char*)&m_data, array.data(), sizeof(DsrHeadEx62));
        //更新界面
        refreshPageUi();
        hsFile.close();
    }

    PromptDialog dialog1;
    dialog1.initDialog(PromptDialog::BTN_OK);
    dialog1.setTitleStr(tr("Prompt"));
    dialog1.setContentStr(tr("Import successful!"));//导入成功！
    dialog1.exec();

}

QString HeadSpacingSheetDialog::intDiv10(int num)
{
    double ret = ((double)num) / 10;
    return QString::number(ret,'f',1);
}

QString HeadSpacingSheetDialog::charToQString(char data)
{
    bitset<8> charBit(data);
    std::string stdStr = to_1string(charBit);
    reverse(stdStr.begin(),stdStr.end());
    QString bitStr = QString::fromStdString(stdStr);
    return bitStr.left(5);
}
